<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar 
        placeholder="输入门店名称" 
        @confirm="handleSearch"
        v-model="searchKeyword"
        radius="40"
      />
    </view>

    <!-- 门店列表 -->
    <scroll-view 
      class="shop-list"
      scroll-y
      @scrolltolower="loadMore"
    >
      <view 
        v-for="(shop, index) in filteredShops" 
        :key="index"
        class="shop-item"
        @click="handleShopDetail(shop)"
      >
        <view class="shop-image">
          <image 
            v-if="shop.storeImage" 
            :src="shop.storeImage" 
            mode="aspectFill"
            class="shop-img"
          />
          <text v-else class="image-placeholder">暂无图片</text>
        </view>

        <view class="shop-content">
          <view class="shop-header">
            <text class="title">{{ shop.storeName }}</text>
            <text class="distance">{{ shop._distance || 0 }}米</text>
          </view>

<!-- 店铺星级代码 -->
          <view class="shop-meta">
			    <!-- 星级图标 -->
            <view class="rating-box">
              <uni-rate 
                :value="shop.score || 3.5" 
                size="14" 
                color="#ffd700"
                margin="2"
                readonly
              />
			  <!-- 数字评分 -->
              <text class="score-text">{{ (shop.score || 3.5).toFixed(1) }}</text>
            </view>
            <text class="sales">已售{{ shop.sales || 0 }}</text>
          </view>

          <view class="info-row">
            <uni-icons type="time" size="14" color="#666" />
            <text>{{ shop.businessHours || '营业时间未提供' }}</text>
          </view>

          <view class="info-row">
            <uni-icons type="location" size="14" color="#666" />
            <text class="address">{{ shop.address }}</text>
          </view>
        </view>
      </view>

      <uni-load-more 
        :status="loading ? 'loading' : 'noMore'" 
        :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '正在加载',
          contentnomore: '暂无更多'
        }"
      />
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const allShops = ref([])
const searchKeyword = ref('')
const loading = ref(false)
const currentLocation = ref({ latitude: 0, longitude: 0 })
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 计算属性过滤店铺
const filteredShops = computed(() => {
  return allShops.value.filter(shop => 
    shop.storeName?.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 初始化加载
onLoad((options) => {
  if (options.lat && options.lng) {
    currentLocation.value = {
      latitude: parseFloat(options.lat),
      longitude: parseFloat(options.lng)
    }
  }
  loadShops()
})

// 加载店铺数据
const loadShops = async (isLoadMore = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    const { data: res } = await uni.request({
      url: 'http://localhost:9587/repairCar/AllStorelist',
      method: 'GET',
      data: {
        page: pagination.value.page,
        pageSize: pagination.value.pageSize,
        lat: currentLocation.value.latitude,
        lng: currentLocation.value.longitude
      }
    })

    const newShops = res.rows.map(item => ({
      ...item,
      _distance: calcDistance(
        currentLocation.value.latitude,
        currentLocation.value.longitude,
        item.latitude,
        item.longitude
      ),
	  // ！！！！！！！！！！！！！！！！星星
      score: item.score || 4.0,
      sales: item.orderCount || 0,
	  id:item.storeId
    }))

    allShops.value = isLoadMore 
      ? [...allShops.value, ...newShops] 
      : newShops

    // 更新分页信息
    pagination.value.total = res.total
    pagination.value.page = res.hasNextPage ? pagination.value.page + 1 : -1

  } catch (error) {
    uni.showToast({ title: '数据加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 距离计算函数
const calcDistance = (lat1, lng1, lat2, lng2) => {
  const rad = d => d * Math.PI / 180
  const R = 6371e3
  const φ1 = rad(lat1)
  const φ2 = rad(lat2)
  const Δφ = rad(lat2 - lat1)
  const Δλ = rad(lng2 - lng1)

  const a = Math.sin(Δφ/2)**2 + Math.cos(φ1)*Math.cos(φ2)*Math.sin(Δλ/2)**2
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  return Math.round(R * c)
}

// 搜索处理（500ms防抖）
let searchTimer = null
const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    allShops.value = [] // 清空当前列表
    pagination.value.page = 1
    loadShops()
  }, 500)
}

// 加载更多
const loadMore = () => {
  if (pagination.value.page === -1) return
  loadShops(true)
}

const handleShopDetail = (shop) => {
  uni.navigateTo({
    url: `/pages/shopDetail/shopDetail?id=${shop.id}`
  })
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background: #f5f5f5;
}

.search-bar {
  margin-bottom: 20rpx;
}

.shop-item {
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 24rpx;
  display: flex;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.shop-image {
  width: 220rpx;
  height: 220rpx;
  border-radius: 8rpx;
  overflow: hidden;
  margin-right: 24rpx;
  background: #f8f8f8;
}

.shop-img {
  width: 100%;
  height: 100%;
}

.image-placeholder {
  color: #ccc;
  font-size: 24rpx;
  line-height: 220rpx;
  text-align: center;
}

.shop-content {
  flex: 1;
}

.shop-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  max-width: 400rpx;
}

.distance {
  font-size: 24rpx;
  color: #666;
}

.shop-meta {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.rating-box {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
}

.score-text {
  font-size: 24rpx;
  color: #ff9000;
  margin-left: 8rpx;
}

.sales {
  font-size: 24rpx;
  color: #666;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
  font-size: 24rpx;
  color: #666;
}

.info-row uni-icons {
  margin-right: 8rpx;
}

.address {
  max-width: 400rpx;
}
</style>